package com.tanhua.sso.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.HuanXinConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author YuShiLong
 * @Date 2021/4/19 19:04
 * @Version 1.0
 */
@Service
public class HuanXinTokenService {

    @Autowired
    private HuanXinConfig huanXinConfig;

    public static final String REDIS_KEY = "HX_TOKEN";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public String getToken() {

        //先校验redis有没有token
        String token = redisTemplate.opsForValue().get(REDIS_KEY);
        if (StringUtils.isNotEmpty(token)) {
            return token;
        }

        return refreshToken();
    }

    private String refreshToken() {

        //访问环信,拼接url
        String url = this.huanXinConfig.getUrl() + this.huanXinConfig.getOrgName() + "/" + this.huanXinConfig.getAppName() + "/token";

        //拼接参数
        HashMap<String, Object> map = new HashMap<>();

        map.put("grant_type", "client_credentials");
        map.put("client_id", this.huanXinConfig.getClientId());
        map.put("client_secret", this.huanXinConfig.getClientSecret());

        //调用restTemplate发送post请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, map, String.class);

        //判断响应是否成功
        if (responseEntity.getStatusCodeValue() != 200) {
            return null;
        }

        String body = responseEntity.getBody();


        try {
            //处理json
            JsonNode jsonNode = MAPPER.readTree(body);
            String accessToken = jsonNode.get("access_token").asText();

            //过期时间提前一天失效
            long expiresIn = jsonNode.get("expires_in").asLong() - 86400;

            //将token放入redis中
            redisTemplate.opsForValue().set(REDIS_KEY, accessToken, expiresIn, TimeUnit.SECONDS);

            return accessToken;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
